#include "scenenode.h"
#include "entity.h"
#include <algorithm>

SceneNode::SceneNode(const std::string &name)
	:mName(name)
	,mChilds()
	,mEntity()
{
}

SceneNode::~SceneNode()
{
	if (mEntity)
	{
		delete mEntity;
		mEntity = 0;
	}
	for(unsigned i = 0; i < mChilds.size(); i++)
	{
		delete mChilds[i];
	}
}

void SceneNode::addChild(SceneNode *node)
{
	if (!node)
		return;
	std::vector<SceneNode*>::iterator it = std::find(mChilds.begin(), mChilds.end(), node);
	if (it == mChilds.end())
		mChilds.push_back(node);
}

SceneNode *SceneNode::getChild(const std::string &name)
{
	for(unsigned i = 0; i < mChilds.size(); i++)
	{
		if (name == mChilds[i]->getName())
			return mChilds[i];
	}
	return NULL;
}

const SceneNode *SceneNode::getChild(const std::string &name)
	const
{
	for(unsigned i = 0; i < mChilds.size(); i++)
	{
		if (name == mChilds[i]->getName())
			return mChilds[i];
	}
	return NULL;
}

Entity* SceneNode::getEntity()
{
	return mEntity;
}

const Entity* SceneNode::getEntity()
	const
{
	return mEntity;
}

void SceneNode::setEntity(Entity *entity)
{
	if (mEntity)
		delete mEntity;
	mEntity = entity;
}

void SceneNode::removeChild(const std::string &name)
{
	unsigned i;
	for(i = 0; i < mChilds.size(); i++)
	{
		if (mChilds[i]->getName() == name)
			break;
	}
	if (i != mChilds.size())
		delete mChilds[i];
}

const std::string &SceneNode::getName()
	const
{
	return mName;
}

void SceneNode::rename(const std::string &name)
{
	mName = name;
}